(function(){
    "use strict";
    var projectStartController=function ($scope,$http,$modal,$location,projectstart_Service,online_testService,
        develop_processService,online_deliveryService,acceptanceService,toolsService){
        //pipeline的配置参数
        $scope.vm = {};

        //根据是否是新项目来初始化$scope.vm的值
        $scope.valueVM =  function (isNew){
            if(isNew == true){
                $scope.vm = {
                    "config" : true,
                    "configCopy" : 'create',
                    "workflow" : {
                        "triggers" : true,
                        "tasks" : [
                            {   "itemId":1,
                                "selected" : false,
                                "isClick" : false,
                                "isSelectShow" : true
                            }

                        ]

                    },
                    "isConfig" : false,
                    "isUpdate" : false
                };
            }else{
                projectstart_Service.getPipeLineConfig({"projectId" : $scope.projectId}).success(function(data){
                    $scope.vm = data.result;
                    if($scope.vm.workflow.tasks.length>0) {
                        $scope.type = $scope.vm.workflow.tasks[0].type;
                    }
                });
            }
        };

        //删除pipe中某个task
        $scope.pipeLineRemove = function(index){
            if($scope.vm.workflow.tasks.length>1){
                $scope.vm.workflow.tasks.splice(index,1);
                //右边配置页面显示下一个task的配置项
                $scope.type = $scope.vm.workflow.tasks[index].type;
            }else if($scope.vm.workflow.tasks.length == 1){
                $scope.vm.workflow.tasks.splice(index,1);
                //右边配置页面显示下一个task的配置项
                $scope.type = {};
            }
        };

        //单击某个task显示task下拉框进行任务选择
        $scope.configTask = function(taskItem){
            //切换成task下拉选择框
            taskItem.isClick = true;
            taskItem.selected = true;
            if(taskItem.type == null || taskItem.type == undefined){
                //新增加一个task
                var task = {
                    "itemId":taskItem.itemId +1,
                    "selected" : false,
                    "isClick" : false,
                    "isSelectShow" : true
                };
                $scope.vm.workflow.tasks.push(task);
//                console.log("id:"+(task.id));
            }
        };

        //单击某个task进行任务配置页的显示
        $scope.configShow = function(taskItem){
            if(taskItem.type != 0){
                console.log("$scope.type:"+taskItem.type);
                $scope.type = taskItem.type;
            }
        };

        //将具体的任务类型固定化
        $scope.taskStyle = [
            {
                "type" : "项目启动",
                "name" : "项目启动"
            },
            {
                "type" : "研发过程",
                "name" : "研发过程"
            },
            {
                "type" : "在线测试",
                "name" : "在线测试"
            },
            {
                "type" : "上线交付",
                "name" : "上线交付"
            },
            {
                "type" : "验收环节",
                "name" : "验收环节"
            }
        ];

        //当前需显示的任务配置页
        $scope.type = {};
        //选择任务类型的方法
        $scope.TSChoose = function(taskItem,selectedTS){
            var result = false;
            angular.forEach($scope.vm.workflow.tasks,function (item) {
                if( selectedTS.type == item.type && !result){
                    result = true;
                }
            });
            //隐藏选择框，显示任务名
            console.log(result);
            if(!result){
                taskItem.isSelectShow = false;
                if(selectedTS != undefined){
                    taskItem.type = selectedTS.type;
                }
            }else{
                $scope.confirmModal(false,selectedTS.name+"已被选，请选择其他任务项!");
            }
        };

        //点击取消按钮，回到项目选择页面（不会执行保存动作）
        $scope.goBack = function (){
            //返回到前一个页面
            parent.iframe.location = "project-select.html";
            //如果项目启动已经保存，则执行后台删除操作(新建项目的操作)
            if($scope.vm.isUpdate == false && $scope.projectId != '0'){
                //将保存的项目信息在数据库中删除
                projectstart_Service.deleteProject({"projectId" : $scope.projectId}).success(function(data){

                });
            }
        };

        //查看tasks队列中是否只有一个"项目启动"的task
        $scope.checkIsConfig = function() {
            console.log("1111"+$scope.isNew);
            if($scope.isNew == false){
                return;
            }
            var result = false;
            var num = 0;
            angular.forEach($scope.vm.workflow.tasks, function(item) {
                if(item.type == "项目启动"){
                    num++;
                }
            });
            if(num == 1){
                result = true;
            }
            return result;
        };
        //监控上述方法的返回值
        $scope.$watch('checkIsConfig()', function(nv) {
            $scope.vm.isConfig = nv;
        });

        //创建流水线的方法
        $scope.createPipeLine = function(){
            if($scope.projectId == '0'){
                $scope.confirmModal(false,"请先成功执行项目启动部分的保存动作 !");
                return;
            }
            //将流水线配置保存到后台
            $scope.vm.isUpdate = true;
            var para = {
                "projectId" : $scope.projectId,
                "vm" : $scope.vm
            };
            projectstart_Service.savePipeLineConfig(para).success(function(data){
                if(data.result == true){
                    //保存成功的情况下执行回显操作
                    var tslength = $scope.vm.workflow.tasks.length;
                    $scope.vm.workflow.tasks.splice(tslength-1,1);
                    //同时将"修改"按钮显示出来
                    // $scope.vm.isUpdate = true;
                    //创建成功的提升对话框
                    $scope.confirmModal(true,"流水线创建成功!");
                }else{
                    $scope.vm.isUpdate = false;
                    $scope.confirmModal(false,"流水线创建失败!");
                }
            });
        };

        //修改流水线的方法(同时保存项目启动部分的修改内容)
        $scope.updatePipeLine = function(){
            //将修改后的流水线配置保存到后台
            var para = {
                "projectId" : $scope.projectId,
                "vm" : $scope.vm
            };
            projectstart_Service.savePipeLineConfig(para).success(function(data){
                if(data.result == true){
                        //保存成功的情况下同时保存项目启动部分的修改内容
                        $scope.saveProjectInfo();
                        //创建成功的提升对话框
                        $scope.confirmModal(true,"流水线创建成功!");
                    }else{
                       $scope.confirmModal(false,"流水线创建失败!");
                    }
                });
            };

            //获取全局变量的项目ID号
            $scope.projectId = '0';
            //该项目是已有项目还是要创建的新项目
            $scope.isNew = true;
            //初始化项目下所有的产品的所有涉及人员信息
            $scope.operators = [];
            //初始化项目下所有的产品信息
            $scope.pros = [];
            $scope.finance = {};
            $scope.addedProductKey=[];
            //save功能-变量定义
            var de_map=[];//开发者
            var tm_map=[];//测试人员
            var listPM=[];//项目经理
            var listBM =[];//部署经理
            //初始化代码仓库类型和jenkins类型
            $scope.codeTypes=["SVN","GIT","GERRIT"];
            $scope.jenkinsTypes = ["java_coverage","php_coverage","python_coverage","findbugs_analysis","pylint_analysis","build_status"];
            //加载5个流水线页面的初始化方法
            $scope.load0 = function (){

            var objid = toolsService.parameter("projectId",$location.absUrl());

            if(objid != null && objid != '0'){
                //该项目是否是新建项目
                $scope.isNew = false;
                //赋值项目ID
                $scope.projectId = objid;
                //显示pipeline
                $scope.valueVM($scope.isNew);
                //当打开的是已有的项目时，显示项目的信息
                $scope.currentProShow($scope.projectId);
                //对产品列表进行赋值
                online_testService.prosGet({projectId : $scope.projectId}).success(function(data){
                    if(true){
                        $scope.pros = data.result;
                    }
                });
                //对需求处理人人员(包括开发，测试，经理)列表进行全局表里赋值
                online_testService.testersGet({projectId : $scope.projectId}).success(function(data){
                    if(true){
                        $scope.operators = data.result;
                        $scope.opers = data.result;
                    }
                });
                $scope.load2();
                $scope.load3();
//                $scope.load4();
                $scope.load5();
                $scope.load6();
                $scope.load7();
                $scope.find();
            }else {
                //显示pipeline
                $scope.valueVM($scope.isNew);
                //加载出项目启动页面所有产品和人员列表
                $scope.load11();
                $scope.load12();
            }
        };

        //项目启动页面部分

        //当打开的是已有的项目时，显示项目的信息
        $scope.currentProShow = function (pid){

            projectstart_Service.getProject(pid).success(function(data){
                if(data.code == "200"){
                    var proinfo = data.result;
                    //将项目信息赋值给本地变量
                    $scope.showProjectName = proinfo.projectName;
                    $scope.newProjectName = proinfo.projectName;
                    $scope.finance.loanDate = proinfo.startDate;
                    $scope.showStartDate = proinfo.startDate;
                    $scope.finance.loanDate1 = proinfo.endDate;
                    $scope.showEndDate = proinfo.endDate;
                    $scope.newProjectDes = proinfo.description;
                    $scope.addedPros = proinfo.products;
                    angular.forEach(proinfo.products,function (product) {
                        $scope.addedProductKey.push(product.productKey);
                        if(product.codeUrl != null){
                            $scope.totalBranchInfo.push({"productKey":product.productKey, "url":product.codeUrl.url,"type":product.codeUrl.type});
                        }
                        if(product.nexusUrl != null) {
                            $scope.totalNexusInfo.push({"productKey": product.productKey, "url": product.nexusUrl.url});
                        }
                        if(product.harborUrl != null) {
                            $scope.totalHarborInfo.push({
                                "productKey": product.productKey,
                                "url": product.harborUrl.url
                            });
                        }
                        if(product.daliyJenkinsUrl != null) {
                            $scope.totalDJenkinsInfo.push({
                                "productKey": product.productKey,
                                "url": product.daliyJenkinsUrl.url,
                                "type": product.daliyJenkinsUrl.type
                            });
                        }
                        if(product.testJenkinsUrl != null) {
                            $scope.totalVJenkinsInfo.push({
                                "productKey": product.productKey,
                                "url": product.testJenkinsUrl.url,
                                "type": product.testJenkinsUrl.type
                            });
                        }
                        if(product.testRailUrl != null) {
                            $scope.totalTRInfo.push({"productKey": product.productKey, "url": product.testRailUrl.url});
                        }
                    });

                    var personAndRoles = proinfo.personAndRoles;
                    for(var key in personAndRoles){
                        angular.forEach(personAndRoles[key],function (item) {
                            if(key == 'PM'){
                                $scope.showProjectManagerName = item.name;
                                $scope.selectedPM = item;
                            }else if(key == 'BM'){
                                $scope.showBuildManagerName = item.name;
                                $scope.selectedDM = item;
                            }else if(key == 'DE'){
                                $scope.addedCoders.push(item);
                                if(de_map!=null){
                                    de_map.push(item.nameKey);
                                }
                            }else if(key == 'TM'){
                                $scope.addedTesters.push(item);
                                if(item!=null) {
                                    tm_map.push(item.nameKey);
                                }
                            }else if(key == 'TESTMANAGER'){
                                $scope.addedTesters.push(item);
                                $scope.showTestManagerName = item.name;
                            }
                        });
                    }
                    //加载出项目启动页面所有产品和人员列表
                    $scope.load11();
                    $scope.load12();
                }else{
                    $scope.confirmModal(false, data.errorMsg);
                }
            });
        };

        //所有产品列表
        $scope.allpros = [];
        //获取所有的产品信息
        $scope.prosGet = function (){
            projectstart_Service.allprojectsGet().success(function(data){
                $scope.allpros = data.result;
            });
        };

        //产品下拉框加载方法
        $scope.load11 = function (){
           $scope.prosGet();
        };

        //选中添加的产品列表
        $scope.addedPros = [];
        $scope.proChoose = function (){
            if($scope.addedPros.length == 0){
                $scope.addedPros.push($scope.selectedPro);
                $scope.addedProductKey.push($scope.selectedPro.productKey);
                //根据选中产品的增减，动态增减对应的开发人员和测试人员信息
                $scope.allCodersGet($scope.addedProductKey);
                $scope.allTestersGet($scope.addedProductKey);
            }else{
                var check = false;
                angular.forEach($scope.addedPros,function (item) {
                    if(!check){
                        if(item.id == $scope.selectedPro.id){
                            check = true;
                        }
                    }
                });
                if(!check){
                    $scope.addedPros.push($scope.selectedPro);
                    $scope.addedProductKey.push($scope.selectedPro.productKey);
                    //根据选中产品的增减，动态增减对应的开发人员和测试人员信息
                    $scope.allCodersGet($scope.addedProductKey);
                    $scope.allTestersGet($scope.addedProductKey);
                }
            }
        };

        //删除对应的选中产品,同时更新选中的开发人员和测试人员列表,以及后面各个仓库的地址信息
        $scope.delPros = function (index){
            //首先将选中框的选中项置为"请选择"状态
            $scope.selectedPro = {};
            var personKeys = $scope.addedPros[index].personKey;
            var people =$scope.addedCoders;
            for (var num=people.length-1;num>=0;num--){
                for(var num1 in personKeys){
                    if(people[num].nameKey ==  personKeys[num1]){
                        $scope.delCoders(num);
                        break;
                    }
                }
            }
            var testers =$scope.addedTesters;
            for (var num=testers.length-1;num>=0;num--){
                for(var num1 in personKeys){
                    if(testers[num].nameKey ==  personKeys[num1]){
                        $scope.delTesters(num);
                        break;
                    }
                }
            }
            $scope.addedPros.splice(index,1);
            $scope.addedProductKey.splice(index,1);
            $scope.allCodersGet($scope.addedProductKey);
            $scope.allTestersGet($scope.addedProductKey);
        };

        //所有的项目经理信息列表
        $scope.allpms = [];
        //获取所有的项目经理信息
        $scope.allPMsGet = function (){
            // var results = [];
            projectstart_Service.allPMsGet().success(function(data){
                // if(data.code == "200"){
                    $scope.allpms = data.result;
                // }
            });
            // return results;
        };

        //所有开发人员信息列表
        $scope.allCoders = [];
        //所有选中产品对应的开发人员信息
        $scope.allCodersGet = function (para){
            // var results = [];
            projectstart_Service.allCodersGet(para).success(function(data){
                // if(data.code == "200"){
                    $scope.allCoders = data.result;
                // }
            });
            // return results;
        };

        //添加开发人员
        $scope.addedCoders = [];
        $scope.coderChoose = function (){
            if($scope.selectedCoder!=undefined){
                $scope.addedCoders.push($scope.selectedCoder);
                de_map.push($scope.selectedCoder.nameKey);
            }
        };

        //删除对应的选中的开发人员
        $scope.delCoders = function (index){
            $scope.selectedCoder = {};
            $scope.addedCoders.splice(index,1);
        };

        //所有测试人员信息列表
        $scope.allTesters = [];
        //所有选中产品对应的测试人员信息
        $scope.allTestersGet = function (para){
            // var results = [];
            projectstart_Service.allTestersGet(para).success(function(data){
                // if(data.code == "200"){
                    $scope.allTesters = data.result;
                // }
            });
            // return results;
        };

        //添加测试人员
        $scope.addedTesters = [];
        $scope.testerChoose = function (){
            if($scope.selectedTester!=undefined) {
                $scope.addedTesters.push($scope.selectedTester);
                tm_map.push($scope.selectedTester.nameKey);
            }
        };

        //删除对应的选中的测试人员
        $scope.delTesters = function (index){
            $scope.selectedTester = {};
            $scope.addedTesters.splice(index,1);
        };

        //所有的实施经理信息列表
        $scope.alldms = [];
        //获取所有的实施经理信息
        $scope.allDMsGet = function (){
            // var results = [];
            projectstart_Service.allDMsGet().success(function(data){
                // if(data.code == "200"){
                $scope.alldms = data.result;
                // }
            });
            // return results;
        };

        //人员分配页面的加载方法
        $scope.load12 = function (){
            //获取所有项目经理列表
            $scope.allPMsGet();
            //获取所有开发人员信息列表

            $scope.allCodersGet($scope.addedProductKey);

            //获取所有测试人员信息列表
            $scope.allTestersGet($scope.addedProductKey);

            //获取所有实施经理列表
            $scope.allDMsGet();
        };

        //监控是否选中产品，未选中的话，保存按钮不可用(代码分支部分)
        $scope.$watch('selectedProBranch',function(newValue, oldValue){
            if(newValue != undefined){
                $scope.isDisabled=false;
            }else{
                $scope.isDisabled=true;
            }
        });

        //监控是否选中产品，未选中的话，保存按钮不可用(Nexus地址部分)
        $scope.$watch('selectedProNexus',function(newValue, oldValue){
            if(newValue != undefined){
                $scope.isDisabled1=false;
            }else{
                $scope.isDisabled1=true;
            }
        });

        //监控是否选中产品，未选中的话，保存按钮不可用(Harbor地址部分)
        $scope.$watch('selectedProHarbor',function(newValue, oldValue){
            if(newValue != undefined){
                $scope.isDisabled2=false;
            }else{
                $scope.isDisabled2=true;
            }
        });

        //监控是否选中产品，未选中的话，保存按钮不可用(日常集成jenkins地址部分)
        $scope.$watch('selectedProDJenkins',function(newValue, oldValue){
            if(newValue != undefined){
                $scope.isDisabled3=false;
            }else{
                $scope.isDisabled3=true;
            }
        });

        //监控是否选中产品，未选中的话，保存按钮不可用(版本测试jenkins地址部分)
        $scope.$watch('selectedProVJenkins',function(newValue, oldValue){
            if(newValue != undefined){
                $scope.isDisabled4=false;
            }else{
                $scope.isDisabled4=true;
            }
        });

        //监控是否选中产品，未选中的话，保存按钮不可用(Testrail地址部分)
        $scope.$watch('selectedProTR',function(newValue, oldValue){
            if(newValue != undefined){
                $scope.isDisabled5=false;
            }else{
                $scope.isDisabled5=true;
            }
        });

        //将填写的信息暂保存在本地(通用方法)
        $scope.saveInfoPerPro = function(totalInfo,subPara,selectedPro,selectedType){
            var info = {};
            if(subPara != undefined && selectedType != undefined){
                info = {
                    productKey : selectedPro.productKey,
                    type:selectedType,
                    url : subPara
                };
            }
            if(totalInfo == undefined){
                totalInfo=[];
                totalInfo.push(info);
            }else{
                var check = false;
                angular.forEach(totalInfo,function (item) {
                    if(!check){
                        if(item.productKey == info.productKey){
                            item.url = subPara;
                            item.type = selectedType;
                            check = true;
                        }
                    }
                });
                if(!check){
                    totalInfo.push(info);
                }
            }
            console.log("本地存储的对象:"+JSON.stringify(totalInfo));
        };

        //动态增减仓库地址的本地存储信息
        $scope.changeLocalInfo = function(totalInfoList,proKey){
            var check = false;
            var tempList = [];
            angular.forEach(totalInfoList,function (item) {
                if(!check){
                    if(item.productKey != proKey){
                        tempList.push(item);
                        check = true;
                    }
                }
            });
            totalInfoList = tempList;
        };

        $scope.totalBranchInfo = [];
        //将产品代码分支信息暂保存在本地
        $scope.saveBranchInfoPerPro = function(){
            if ($scope.selectedCodeType == undefined) {
                $scope.confirmModal(false, "请选择类型!!!");
            } else {
                $scope.saveInfoPerPro($scope.totalBranchInfo, $scope.subBranchInfo, $scope.selectedProBranch, $scope.selectedCodeType);
            }
        };
        //修改产品代码信息左侧的选中产品
        $scope.proBranchChoose = function (){
            if($scope.selectedProBranch == undefined){
                $scope.subBranchInfo = '';
                return;
            }
            if($scope.selectedCodeType == undefined){
                $scope.subBranchInfo = '';
                return;
            }
            var check = false;
            angular.forEach($scope.totalBranchInfo,function (item) {
                if(!check){
                    if(item.productKey == $scope.selectedProBranch.productKey
                        && item.type == $scope.selectedCodeType){
                        $scope.subBranchInfo = item.url;
                        check = true;
                    }
                }
            });
            if(!check){
                $scope.subBranchInfo = '';
            }
        };

        $scope.totalNexusInfo = [];
        //将Nexus仓库地址信息暂存在本地
        $scope.saveNexusInfoPerPro = function (){
            $scope.saveInfoPerPro($scope.totalNexusInfo, $scope.subNexusInfo, $scope.selectedProNexus,"");
        };
        //修改Nexus仓库地址左侧的选中产品
        $scope.proNexusChoose = function (){
            if($scope.selectedProNexus == undefined){
                $scope.subNexusInfo = '';
                return;
            }
            var check = false;
            angular.forEach($scope.totalNexusInfo,function (item) {
                if(!check){
                    if(item.productKey == $scope.selectedProNexus.productKey){
                        $scope.subNexusInfo = item.url;
                        check = true;
                    }
                }
            });
            if(!check){
                $scope.subNexusInfo = '';
            }
        };

        $scope.totalHarborInfo = [];
        //将Harbor仓库地址信息暂存在本地
        $scope.saveHarborInfoPerPro = function (){
            $scope.saveInfoPerPro($scope.totalHarborInfo, $scope.subHarborInfo, $scope.selectedProHarbor,"");
        };
        //修改Harbor仓库地址左侧的选中产品
        $scope.proHarborChoose = function (){
            if($scope.selectedProHarbor == undefined){
                $scope.subHarborInfo = '';
                return;
            }
            var check = false;
            angular.forEach($scope.totalHarborInfo,function (item) {
                if(!check){
                    if(item.productKey == $scope.selectedProHarbor.productKey){
                        $scope.subHarborInfo = item.url;
                        check = true;
                    }
                }
            });
            if(!check){
                $scope.subHarborInfo = '';
            }
        };

        $scope.totalDJenkinsInfo = [];
        //将日常集成jenkins地址信息暂存在本地
        $scope.saveDJenkinsInfoPerPro = function (){
            if ($scope.selectedJenkinsDailyType == undefined) {
                $scope.confirmModal(false, "请选择类型!!!");
            } else {
                $scope.saveInfoPerPro($scope.totalDJenkinsInfo, $scope.subDJenkinsInfo, $scope.selectedProDJenkins,$scope.selectedJenkinsDailyType);
            }
        };
        //修改日常集成jenkins地址左侧的选中产品
        $scope.proDJenkinsChoose = function (){
            if($scope.selectedProDJenkins == undefined){
                $scope.subDJenkinsInfo = '';
                return;
            }
            if($scope.selectedJenkinsDailyType == undefined){
                $scope.subDJenkinsInfo = '';
                return;
            }
            var check = false;
            angular.forEach($scope.totalDJenkinsInfo,function (item) {
                if(!check){
                    if(item.productKey == $scope.selectedProDJenkins.productKey
                        && item.type == $scope.selectedJenkinsDailyType){
                        $scope.subDJenkinsInfo = item.url;
                        check = true;
                    }
                }
            });
            if(!check){
                $scope.subDJenkinsInfo = '';
            }
        };

        $scope.totalVJenkinsInfo = [];
        //将版本测试jenkins地址信息暂存在本地
        $scope.saveVJenkinsInfoPerPro = function () {
            if ($scope.selectedJenkinsType == undefined) {
                $scope.confirmModal(false, "请选择类型!!!");
            } else {
                $scope.saveInfoPerPro($scope.totalVJenkinsInfo, $scope.subVJenkinsInfo, $scope.selectedProVJenkins, $scope.selectedJenkinsType);
            }
        };
        //修改版本测试jenkins地址左侧的选中产品
        $scope.proVJenkinsChoose = function (){
            if($scope.selectedProVJenkins == undefined){
                $scope.subVJenkinsInfo = '';
                return;
            }
            if($scope.selectedJenkinsType == undefined){
                $scope.subVJenkinsInfo = '';
                return;
            }
            var check = false;
            angular.forEach($scope.totalVJenkinsInfo,function (item) {
                if(!check){
                    if(item.productKey == $scope.selectedProVJenkins.productKey
                        && item.type == $scope.selectedJenkinsType){
                        $scope.subVJenkinsInfo = item.url;
                        check = true;
                    }
                }
            });
            if(!check){
                $scope.subVJenkinsInfo = '';
            }
        };

        $scope.totalTRInfo = [];
        //将Testrail地址信息暂存在本地
        $scope.saveTRInfoPerPro = function (){
            $scope.saveInfoPerPro($scope.totalTRInfo, $scope.subTRInfo, $scope.selectedProTR,"");
        };
        //修改Testrail地址左侧的选中产品
        $scope.proTRChoose = function (){
            if($scope.selectedProTR == undefined){
                $scope.subTRInfo = '';
                return;
            }
            var check = false;
            angular.forEach($scope.totalTRInfo,function (item) {
                if(!check){
                    if(item.productKey == $scope.selectedProTR.productKey){
                        $scope.subTRInfo = item.url;
                        check = true;
                    }
                }
            });
            if(!check){
                $scope.subTRInfo = '';
            }
        };

        //日期控件
        $scope.dateOptions = {
             startingDay: 1,
             class: 'datepicker'
        };
        //日期控件
        $scope.format = "yyyy-MM-dd";
        $scope.openDatepicker = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if(i==1){
                $scope.loanDate = true;
            }
        };

        $scope.openDatepicker1 = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if(i==1){
                $scope.loanDate1 = true;
            }
        };

        //保存项目信息的方法(需加上错误提示对话框)
        $scope.saveProjectInfo = function (){
            var sDate = new Date($scope.finance.loanDate);
            var eDate = new Date($scope.finance.loanDate1);
            if(sDate.getTime() >= eDate.getTime()){
                $scope.confirmModal(false,"开始日期不能晚于结束日期 !");
                return;
            }
            if($scope.newProjectName == undefined){
                $scope.confirmModal(false,"项目名称项不能为空 !");
                return;
            }
            if($scope.finance.loanDate == undefined || $scope.finance.loanDate1 == undefined){
                $scope.confirmModal(false,"项目启动和结束日期不能为空 !");
                return;
            }
            if($scope.selectedPM == undefined){
                $scope.confirmModal(false,"请添加项目经理 !");
                return;
            }else{
                listPM.push($scope.selectedPM.nameKey);
            }
            if($scope.selectedDM == undefined){
                $scope.confirmModal(false,"请添加部署经理 !");
                return;
            }else {
                listBM.push($scope.selectedDM.nameKey);
            }
            if($scope.addedProductKey == undefined || $scope.addedProductKey.length <= 0){
                $scope.confirmModal(false,"请添加产品 !");
                return;
            }
            if(tm_map == undefined || tm_map.length <= 0){
                $scope.confirmModal(false,"请添加测试人员 !");
                return;
            }
            if(de_map == undefined || de_map.length <= 0){
                $scope.confirmModal(false,"请添加开发人员 !");
                return;
            }
            //入参增加objectid参数，后台判断是否为'0',为0的话就是新建的项目
            var para = {
                projectId : $scope.projectId,
                projectName : $scope.newProjectName,
                startDate : sDate,
                endDate : eDate,
                description : $scope.newProjectDes,
                personKeyAndRoles: {"PM":listPM,"TM":tm_map,"BM":listBM,"DE":de_map},
                productKeys : $scope.addedProductKey,
                codeUrl : $scope.totalBranchInfo,
                nexusUrl : $scope.totalNexusInfo,
                harborUrl : $scope.totalHarborInfo,
                daliyJenkinsUrl : $scope.totalDJenkinsInfo,
                testJenkinsUrl : $scope.totalVJenkinsInfo,
                testRailUrl : $scope.totalTRInfo
            };
           projectstart_Service.newProjectSave(para).success(function(data){
               if(data.code == '200'){
                   //对objectId进行赋值
                   $scope.projectId = data.result;
                   //当更新项目信息之后需对产品列表重新赋值
                   online_testService.prosGet({projectId : data.result}).success(function(data){
                       if(true){
                           $scope.pros = data.result;
                       }
                   });
                   //当更新项目信息之后需对需求处理人人员(包括开发，测试，经理)列表进行重新赋值
                   online_testService.testersGet({projectId : data.result}).success(function(data){
                       if(true){
                           $scope.operators = data.result;
                           $scope.opers = data.result;
                       }
                   });
                   //用于回显页头的项目人员信息
                   projectstart_Service.getProject(data.result).success(function(data){
                       $scope.showProjectName = data.result.projectName;
                       $scope.showProjectManagerName =  data.result.personAndRoles.PM[0].name;
                       $scope.showTestManagerName = data.result.personAndRoles.TM[0].name;
                       $scope.showBuildManagerName = data.result.personAndRoles.BM[0].name;
                       $scope.showStartDate = data.result.startDate;
                       $scope.showEndDate = data.result.endDate;
                   });
                   //在线测试页面第一个tab页(测试结果)柱形图初始化方法
                   // $scope.load1();
                   //在线测试页面第二个tab页(版本测试)初始化方法
                   $scope.load2();
                   //研发过程页面第一个tab页(项目需求)初始化方法
                   $scope.load3();
                   //研发过程页面第二个tab页(代码审计)初始化方法
                   $scope.load4();
                   //研发过程页面第三个tab页(构建信息)初始化方法
                   $scope.load5();
                   //上线交付页面第一个tab页(可选部署包)初始化方法
                   $scope.load6();
                   //上线交付页面第二个tab页(历史记录)初始化方法
                   $scope.load7();
                   //验收环节页面初始化方法
                   $scope.find();

                   //保存成功提示框
                   $scope.confirmModal(true,"保存成功!");
               }else {
                   $scope.confirmModal(false, data.errorMsg);
               }
           });
        };

        //研发过程第一个tab页面(项目需求)部分
        //关键字搜索信息
        $scope.keyword = '';
        //项目某个产品下所有需求的处理人集合
        $scope.opers = '';
        //显示的需求信息
        $scope.requirements = [];

        //初始化状态参数
        $scope.status = ["所有状态","Open","In Progress","Reopened","Resolved","Closed","In Review","待处理","完成","Deploy","SIT"];

        //初始化需求类型参数
        $scope.kinds = ["所有类型","部署","子任务","任务","文档","改进","运维支持","缺陷","需求","新特性","测试","Story",
                            "工作项","【工单】开发需求","调研","Epic","Technical task","培训","服务申请","【工单】技术服务",
                            "【工单】故障申报","基线申请","会议","售后","RDS new task"];

        //初始化优先级类型参数
        $scope.prioritys = ["所有优先级","Blocker","Critical","Major","Minor","Trivial"];

        //根据产品，处理人，状态，类型，优先级级别，关键字查找对应产品的所有需求信息
        $scope.requirementsSearch = function (request){
            develop_processService.requirementsGet(request).success(function(data){
                if(true){
                    $scope.requirements = data.result;
                    $scope.totalItems = data.totalCount;
                }
            });
        };

        //根据选中的产品获取对应的需求处理人
        // $scope.opersGet = function (request){
        //     develop_processService.operatorsGet(request).success(function(data){
        //         if(true){
        //             $scope.opers = data.result;
        //         }
        //     });
        // };

        //分页参数
        $scope.currentPageNum=5;
        $scope.totalItems={};
        //每页显示条数(默认5条)
        $scope.count="20";

        $scope.page = 1;

        //初始化项目需求tab页面
        $scope.load3 = function (){
            $scope.proChange2(1);
        };

        //修改选中的产品
        $scope.proChange2 = function (page){
            // console.log("当前选择的产品ID:"+$scope.selectedPro2.id+$scope.selectedPro2.productName);
            //根据选中的产品获取对应的需求处理人
            if($scope.selectedPro2 != undefined){
                // var request = {
                //     projectId : $scope.projectId,
                //     productKey : $scope.selectedPro2.productKey
                // };
                // $scope.opersGet(request);
            }

            //根据下拉框的选项显示符合要求的需求信息
            var requestDev={projectId:$scope.projectId};
            if($scope.selectedPro2 != undefined){
                requestDev.productKey=$scope.selectedPro2.productKey;
            }else{
                requestDev.productKey="";
            }
            if($scope.selectedOper2 != undefined){
                requestDev.personKey=$scope.selectedOper2.nameKey;
            }else{
                requestDev.personKey="";
            }
            if($scope.keyword != undefined){
                requestDev.productTitle = $scope.keyword;
            }
            if($scope.selectedStatus2 != undefined && $scope.selectedStatus2!="所有状态"){
                requestDev.productStatus = $scope.selectedStatus2;
            }else{
                requestDev.productStatus ="";
            }
            if($scope.selectedKind2 != undefined && $scope.selectedKind2!="所有类型"){
                requestDev.productType = $scope.selectedKind2;
            }else{
                requestDev.productType ="";
            }
            if($scope.selectedPriority2 != undefined && $scope.selectedPriority2!="所有优先级"){
                requestDev.level = $scope.selectedPriority2;
            }else{
                requestDev.level ="";
            }

            //新增2个分页参数
            var requestDevPage = {baseModel:requestDev};
            requestDevPage.startIndex = (page - 1) * $scope.count;
            requestDevPage.count = $scope.count;

            $scope.requirementsSearch(requestDevPage);

            //显示各个状态需求的数量
            $scope.requirementSummary();
        };

        //修改选择的处理人
        $scope.operChange2 = function (page){
            //根据下拉框的选项显示符合要求的需求信息
            var requestDev={projectId:$scope.projectId};
            if($scope.selectedPro2 != undefined){
                requestDev.productKey=$scope.selectedPro2.productKey;
            }else{
                requestDev.productKey="";
            }
            if($scope.selectedOper2 != undefined){
                requestDev.personKey=$scope.selectedOper2.nameKey;
            }else{
                requestDev.personKey="";
            }
            if($scope.keyword != undefined){
                requestDev.productTitle = $scope.keyword;
            }
            if($scope.selectedStatus2 != undefined && $scope.selectedStatus2!="所有状态"){
                requestDev.productStatus = $scope.selectedStatus2;
            }else{
                requestDev.productStatus ="";
            }
            if($scope.selectedKind2 != undefined && $scope.selectedKind2!="所有类型"){
                requestDev.productType = $scope.selectedKind2;
            }else{
                requestDev.productType ="";
            }
            if($scope.selectedPriority2 != undefined && $scope.selectedPriority2!="所有优先级"){
                requestDev.level = $scope.selectedPriority2;
            }else{
                requestDev.level ="";
            }

            //新增2个分页参数
            var requestDevPage = {baseModel:requestDev};
            requestDevPage.startIndex = (page - 1) * $scope.count;
            requestDevPage.count = $scope.count;

            $scope.requirementsSearch(requestDevPage);
            //显示各个状态需求的数量
            $scope.requirementSummary();
        };

        //修改选择的需求状态、优先级、类型以及关键字搜索
        $scope.statusChange2 = function (){
            $scope.operChange2(1);
        };

        $scope.todoRequirementNum = 0;
        $scope.doingRequirementNum = 0;
        $scope.doneRequirementNum = 0;
        //统计total,doing,done这三种状态的需求数量
        $scope.requirementSummary = function (){
            //每次调用前就初始化为0
            $scope.todoRequirementNum = 0;
            $scope.doingRequirementNum = 0;
            $scope.doneRequirementNum = 0;
            angular.forEach($scope.requirements,function (item) {
                if(item.status == '未开始'){
                    $scope.todoRequirementNum++;
                }else if(item.status == '处理中'){
                    $scope.doingRequirementNum++;
                }else if(item.status == '已完成'){
                    $scope.doneRequirementNum++;
                }
            });
        };

        //第二个tab页面（代码审计）部分
        $scope.timedimensions = ["DAY","WEEK","MONTH"];

        //获取代码审计结果，并柱状图显示
        $scope.codeInfoGet = function(projectId,productId,timeType){
            $scope.clearTable2();
            var paras = {
                projectId : projectId,
                productId : productId,
                timeType : timeType
            };
            develop_processService.codeInfoGet(paras).success(function(data){
                var result = data.result;
                if(result != null){
                    $scope.initTable2(result);
                }
            });
        };

        //画柱形图表
        $scope.chart2 = new h5Charts.SerialChart();
        $scope.chart21 = new h5Charts.SerialChart();
        $scope.chart22 = new h5Charts.SerialChart();
        $scope.initTable2 = function(codeInfoResponse){
            if(codeInfoResponse == null){
                return;
            }

            var dataProvider = [];
            var dataProvider1 = [];
            var dataProvider2 = [];
            var colorList = [];
            if (codeInfoResponse.commitInfoList != null && codeInfoResponse.commitInfoList.length > 0){
                angular.forEach(codeInfoResponse.commitInfoList,function (item) {
                    colorList.push("#00B47A");

                    var obj1 = {};
                    obj1.name = item.coderName ;
                    obj1.num = item.codeNumIncreased ;
                    dataProvider1.push(obj1);
                });
            }

            if (codeInfoResponse.codeInfoList != null && codeInfoResponse.codeInfoList.length > 0){
                angular.forEach(codeInfoResponse.codeInfoList,function (item) {
                    var obj = {};
                    obj.name = item.coderName ;
                    obj.num = item.requirementsNum ;
                    dataProvider.push(obj);
                    colorList.push("#00B47A");
                });
            }

            if (codeInfoResponse.costTimeList != null && codeInfoResponse.costTimeList.length > 0){
                angular.forEach(codeInfoResponse.costTimeList,function (item) {
                    var obj2 = {};
                    obj2.name = item.coderName ;
                    obj2.num = item.costTime ;
                    dataProvider2.push(obj2);
                });
            }



            if (dataProvider1 != null && dataProvider1.length > 0){
                $scope.chart21.dataProvider = dataProvider1;
                $scope.chart21.categoryField = "name";
                $scope.chart21.valueField = "num";
                $scope.chart21.type = "column";
                $scope.chart21.columnWidth = 10;
                $scope.chart21.colors = colorList;
                $scope.chart21.addTo("codenumsubmit");
            }
            if (dataProvider != null && dataProvider.length > 0){
                $scope.chart2.dataProvider = dataProvider;
                $scope.chart2.categoryField = "name";
                $scope.chart2.valueField = "num";
                $scope.chart2.type = "column";
                $scope.chart2.columnWidth = 10;
                $scope.chart2.colors = colorList;
                $scope.chart2.addTo("requirementdone");
            }
            if (dataProvider2 != null && dataProvider2.length > 0){

                $scope.chart22.dataProvider = dataProvider2;
                $scope.chart22.categoryField = "name";
                $scope.chart22.valueField = "num";
                $scope.chart22.type = "column";
                $scope.chart22.columnWidth = 10;
                $scope.chart22.colors = colorList;
                $scope.chart22.addTo("costtime");
            }


        };

        //清空画布内容
        $scope.clearTable2 = function (){
            var canvas1=document.getElementById("requirementdone");
            var cxt1=canvas1.getContext("2d");
            cxt1.clearRect(0,0,canvas1.width,canvas1.height);

            var canvas2=document.getElementById("codenumsubmit");
            var cxt2=canvas2.getContext("2d");
            cxt2.clearRect(0,0,canvas2.width,canvas2.height);

            var canvas3=document.getElementById("costtime");
            var cxt3=canvas3.getContext("2d");
            cxt3.clearRect(0,0,canvas3.width,canvas3.height);
        };

        //初始化代码审计tab页面
        $scope.load4 = function (){
            $scope.pro1Change2();
        };

        //改变选中的产品
        $scope.pro1Change2 =  function (){
            if($scope.selectedPro21!=undefined){
                $scope.codeInfoGet(
                    $scope.projectId,
                    $scope.selectedPro21.productKey,
                    $scope.selectedTimedimension2
                );
            }else{
                $scope.codeInfoGet(
                    $scope.projectId,
                    $scope.allpros[0].productKey,
                    $scope.selectedTimedimension2
                );
            }

        };

        //改变选中的时间度量
        $scope.timedimensionChange2 = function (){
            $scope.pro1Change2();
        };

        //第三个tab页面（构建信息）部分
        $scope.latestBuildRecords = [];
        //将boolean变量值转化成白字
        $scope.transferResult = function (var1){
            if(var1){
                return "成功" ;
            }else {
                return "失败" ;
            }
        };

        //初始化构建信息tab页面
        $scope.load5 =  function (){
            if($scope.projectId == null || $scope.projectId == undefined || $scope.projectId == 0){
                return;
            }
            var paras = {
                projectId : $scope.projectId
            };
            var results = [];
            develop_processService.latestBuildInfo(paras).success(function(data){
                if(data.result.length > 0){
                    results = data.result;
                    angular.forEach(results,function (item) {
                        var tem = {
                            productName : item.productName,
                            productKey : item.productKey,
                            date : item.date,
                            isCheckOut : $scope.transferResult(item.isCheckOut),
                            isBuild : $scope.transferResult(item.isBuild),
                            highPriorityNum : item.highPriorityNum,
                            normalPriorityNum : item.normalPriorityNum,
                            coverageReport : item.coverageReport
                        };
                        $scope.latestBuildRecords.push(tem);
                    });
                }
            });


        };


        //在线测试页面第一个tab页面(测试结果)部分
        $scope.productionId = '';

        //改变选中的产品
        $scope.proChange3 = function (){
            // console.log("当前选择的产品ID:"+$scope.selectedPro3.id+$scope.selectedPro3.productName);
            $scope.productionId = $scope.selectedPro3.productKey;
            $scope.onlineTestProcessGet($scope.projectId,
                                    $scope.productionId,
                                    $scope.selectedTimedimension3);
        };

//        $scope.timedimensions = ["DAY","WEEK","MONTH"];
        //日期下拉框的change事件方法
        $scope.timedimensionChange3 = function (){
            if($scope.productionId != ''){
                $scope.onlineTestProcessGet($scope.projectId,
                                    $scope.productionId,
                                    $scope.selectedTimedimension3
                );
            }
        };
        //获取测试进展信息
        $scope.onlineTestProcessGet = function (projectId,productionId,timedimensions){
            $scope.clearTable();
            var requestJson = {
                projectId : projectId,
                productionId : productionId,
                timedimensions : timedimensions
            };
            online_testService.testProcessGet(requestJson).success(function(data){
                if(data.code==200 && data.result != null){
                    var testProgress = data.result;
                    $scope.initTable(testProgress);
                }
            });
        };

        //在线测试页面测试结果tab页柱形图初始化方法
        $scope.load1 = function(){
            if($scope.projectId == ''){
                return;
            }
            var testProcessData = $scope.onlineTestProcessGet($scope.projectId,
                                 $scope.selectedPro3.productKey,
                                 $scope.selectedTimedimension3);
        };

        //画柱形图表
        $scope.chart = new h5Charts.SerialChart();
        $scope.chart1 = new h5Charts.SerialChart();
        $scope.chart2 = new h5Charts.SerialChart();
        $scope.initTable = function(testProcessData){
            if(typeof(testProcessData)== "undefined"){
                return;
            }

            var dataProvider = [];
            var dataProvider1 = [];
            var dataProvider2 = [];
            var colorList = [];
            if (testProcessData.testrailInfoList != null && testProcessData.testrailInfoList.length > 0){
                angular.forEach(testProcessData.testrailInfoList,function (item) {
                    var obj = {};
                    obj.name = item.testerName ;
                    obj.num = item.testRailCaseNum ;
                    dataProvider.push(obj);
                    colorList.push("#00B47A");
                });
            }

            if (testProcessData.onlineTestInfosList != null && testProcessData.onlineTestInfosList.length > 0){
                angular.forEach(testProcessData.onlineTestInfosList,function (item) {
                    colorList.push("#00B47A");

                    var obj1 = {};
                    obj1.name = item.testerName ;
                    obj1.num = item.jiraNewBugNum ;
                    dataProvider1.push(obj1);

                    var obj2 = {};
                    obj2.name = item.testerName ;
                    obj2.num = item.jiraValidBugNum ;
                    dataProvider2.push(obj2);
                });
            }

            if (dataProvider != null && dataProvider.length > 0) {
                $scope.chart.dataProvider = dataProvider;
                $scope.chart.categoryField = "name";
                $scope.chart.valueField = "num";
                $scope.chart.type = "column";
                $scope.chart.columnWidth = 30;
                $scope.chart.colors = colorList;
                $scope.chart.addTo("donetestcases");
            }

            if (dataProvider1 != null && dataProvider1.length > 0) {
                $scope.chart1.dataProvider = dataProvider1;
                $scope.chart1.categoryField = "name";
                $scope.chart1.valueField = "num";
                $scope.chart1.type = "column";
                $scope.chart1.columnWidth = 30;
                $scope.chart1.colors = colorList;
                $scope.chart1.addTo("addbugs");
            }

            if (dataProvider2 != null && dataProvider2.length > 0) {
                $scope.chart2.dataProvider = dataProvider2;
                $scope.chart2.categoryField = "name";
                $scope.chart2.valueField = "num";
                $scope.chart2.type = "column";
                $scope.chart2.columnWidth = 30;
                $scope.chart2.colors = colorList;
                $scope.chart2.addTo("validbugs");
            }


        };

        //清空画布内容
        $scope.clearTable = function (){
            var canvas1=document.getElementById("donetestcases");
            var cxt1=canvas1.getContext("2d");
            cxt1.clearRect(0,0,canvas1.width,canvas1.height);

            var canvas2=document.getElementById("addbugs");
            var cxt2=canvas2.getContext("2d");
            cxt2.clearRect(0,0,canvas2.width,canvas2.height);

            var canvas3=document.getElementById("validbugs");
            var cxt3=canvas3.getContext("2d");
            cxt3.clearRect(0,0,canvas3.width,canvas3.height);
        };

        //在线测试页面第二个tab页面(版本测试)部分

        //获取jenkins里的最新构建信息记录
        $scope.buildRecords = [];
        $scope.buildRecordsGet = function (){
            if($scope.projectId == ''){
                return;
            }
            var para = {
                projectId : $scope.projectId
            };
            online_testService.latestBuildInfoGet(para).success(function(data){
                if(data.result == true){
                    angular.forEach(data.latestBuildInfoList,function (item) {
                        var temVar = {
                            productionName : item.productionName,
                            buildDate : item.buildDate,
                            buildTime : item.buildTime,
                            isCheckout : $scope.transferResult(item.isCheckout),
                            isBuild : $scope.transferResult(item.isBuild),
                            highBugNum : item.highBugNum,
                            normalBugNum : item.normalBugNum,
                            coverageReport : item.coverageReport,
                            isGenerateTarFile : $scope.transferResult(item.isGenerateTarFile),
                            isUploadToTestLib : $scope.transferResult(item.isUploadToTestLib),
                            isDeployTestEnvironment : $scope.transferResult(item.isDeployTestEnvironment),
                            isUploadToStableLib : $scope.transferResult(item.isUploadToStableLib)
                        };
                        $scope.buildRecords.push(temVar);
                    });
                }else{
                    console.log('Get codeBuild information error !');
                }
            });
        };

        //获取最新提测信息记录
        $scope.testStartRecords = [];
        $scope.testStartRecordsGet = function (){
            if($scope.projectId == ''){
                return;
            }
            var para = {
                projectId : $scope.projectId
            };
            online_testService.latestTestStartInfoGet(para).success(function(data){
                if(true){
                    $scope.testStartRecords = data.result;
                }
            });
        };

        //在线测试页面第二个tab页（版本测试）页面的初始化方法
        $scope.load2 = function(){
            $scope.buildRecordsGet();
            $scope.testStartRecordsGet();
        };

        //刷新显示版本页面
        $scope.refreshTestStartRecords = function(){
            $scope.testStartRecordsGet();
            console.log('刷新成功 !');
        };

        //删除选中的提测信息记录
        $scope.deleteInfo = function(index){
            var selectedTestStartRecord = $scope.testStartRecords[index];
            $scope.testStartRecords.splice(index,1);
            var paras = {
                deleteId : selectedTestStartRecord.id
            };
            online_testService.testStartInfoDel(paras).success(function(data){
                if(data.result == true){
                    //需要增加提示框
                    $scope.confirmModal(true,"delete successfully !");
                }else{
                    //需要增加提示框
                    $scope.confirmModal(false,"delete failed !");
                }
            });
        };

        //构建选中的提测信息记录
        $scope.buildOnJenkins = function(index){
            var selectedTestStartRecord = $scope.testStartRecords[index];
            var paras = {
                productionName : selectedTestStartRecord.productionName,
                versionNum : selectedTestStartRecord.versionNum,
                branchName : selectedTestStartRecord.branchName
            };
            online_testService.buildOnJenkins(paras).success(function(data){
                if(data.result == true){
                    //需要增加提示框
                    $scope.confirmModal(true,"build successfully !");
                    console.log('build successfully !');
                }else{
                    //需要增加提示框
                    $scope.confirmModal(false,"build failed !");
                    console.log('build failed !');
                }
            });
        };

        //对选中的提测信息记录进行部署包归档
        $scope.uploadTarFile = function(index){
            var selectedTestStartRecord = $scope.testStartRecords[index];
            var para = {
                productionName : selectedTestStartRecord.productionName,
                versionNum : selectedTestStartRecord.versionNum
            };
            online_testService.uploadTarFile(para).success(function(data){
                if(data.result == true){
                    //需要增加提示框
                    $scope.confirmModal(true,"uploadTarFile successfully !");
                    console.log('uploadTarFile successfully !');
                }else{
                    //需要增加提示框
                    $scope.confirmModal(false,"uploadTarFile successfully !");
                    console.log('uploadTarFile failed !');
                }
            });
        };

        //打开新增对话框
        $scope.addTestStartRecord = function(){
             $scope.paras = {
                pros : $scope.pros,
                teststarters : $scope.opers,
                testers : $scope.operators
            };
            var modalInstance = $modal.open({
                templateUrl : 'myModalContent.html',
                controller : modalInstanceCtrl,
                keyboard : false,
                backdrop : false,
                resolve : {
                    paras : function () {
                        return angular.copy($scope.paras);
                    }
                }
            });
            modalInstance.result.then(function(data) {
                //在后台数据库保存新增记录
                var para = {
                    projectId : $scope.projectId,
                    iterationTestInfo : data
                };
                online_testService.newTestStartInfoAdd(para).success(function(data){
                    if(true){
                        //保存成功的情况下刷新表格
                        $scope.refreshTestStartRecords();
                    }else{
                        //需要增加提示框，需确认下对话框里加对话框是否可行?
                        $scope.confirmModal(false,"New Record save successfully !");
                        console.log('New Record save failed !');
                    }
                });
            });
        };

        //上线交付页面部分
        //项目下所有产品的版本信息
        $scope.prosInProject = [];
        //项目下的涉及人员信息
        $scope.personsInfo = {};
        //获取项目的所有产品的版本号信息(包括每个版本的下载地址)
        $scope.prosVersionGet = function (){
            if($scope.projectId == ''){
                return;
            }
            var para = {
                projectId : $scope.projectId
            };
            online_deliveryService.getProductForDown(para).success(function(data){
                if(data.result != null){
                    $scope.prosInProject = data.result;
                    angular.forEach($scope.prosInProject,function (item) {
                        item.showList = [];
                        angular.forEach(item.versionList,function (version) {
                            var showBean = {
                                version:version
                            };
                            item.showList.push(showBean);
                        });
                    });
                }
            });
        };

        //获取某个项目的涉及人员信息（pm,dm,tester等人员姓名、联系方式以及项目名称）
        $scope.personsinfoGet = function (){
            if($scope.projectId == ''){
                return;
            }

            projectstart_Service.getProject($scope.projectId).success(function(data){
                if(data.result != null && data.result.length > 0){
                    $scope.personsInfo = data.result;
                    $scope.projectName = $scope.personsInfo.projectName;
                }
            });
        };

        //第一个tab页面(可选部署包)的初始化方法
        $scope.load6 = function (){
            //获取该项目下所有产品的版本信息
           $scope.prosVersionGet();
           $scope.personsinfoGet();
        };

        //下载部署包到本地，并将下载记录保存到数据库（后台实现）
        $scope.download = function (){
            if($scope.projectId == ''){
                return;
            }
            var param = {
                downloadDirs : []
            };
            var projectId = $scope.projectId;
            var selectList = $scope.prosInProject;

            //数据提交
            var record = {
                projectId : projectId,
                downloadedProducts : ""
            };
            angular.forEach(selectList,function (item) {
                angular.forEach(item.showList,function (show) {
                    if(item.selectVersion == null && show.state == true){
                        item.selectVersion = show.version;
                    }
                });
                if(item.selectVersion != null){
                    var product = {
                        id:item.bdfProduct.id,
                        type:"2",
                        version:item.selectVersion,
                        path:$scope.path
                    };
                    param.downloadDirs.push(product);
                    record.downloadedProducts += ""+item.productName +":"+item.selectVersion+";";
                }
            });
            if(param.downloadDirs.length == 0){
                alert("未选择产品或套件版本，请检查！");
                return;
            }
            var length = record.downloadedProducts.lastIndexOf(";");
            record.downloadedProducts = record.downloadedProducts.substr(0,length);

            online_deliveryService.downloadtarfile(param).success(function(data){
                if(data.errorMsg != null){
                    alert(data.errorMsg,1000);
                } else {
                    var fileName = data.fileName;
                    online_deliveryService.savedownloadhistoryrecords(record).success(function () {
                        $scope.loading = false;
                        if(data.errorMsg != null){
                            $.Huimodalalert(data.errorMsg,1000);
                        } else {
                            //特殊字符+，&转义处理
                            fileName = fileName.replace(/\+/g, "%2B");
                            fileName = fileName.replace(/\&/g, "%26");
                            window.location.href = "/api/file/download?type=1&fileName=" + fileName;
                        }
                    });
                }
            });
        };

        //用来存储tar包下载历史记录
        $scope.downloadHistoryRecords = [];
        //上线支付页面第二个tab页（历史记录）中显示该项目部署的tar包历史下载记录
        $scope.downloadhistoryrecordsGet = function (){
            if($scope.projectId == ''){
                return;
            }
            var result = [];
            var para = {
                projectId : $scope.projectId
            };
            online_deliveryService.showdownloadhistoryrecords(para).success(function(data){
                if(data.result != null && data.result.length > 0){
                    $scope.downloadHistoryRecords = data.result;
                    angular.forEach($scope.downloadHistoryRecords,function (item) {
                       if (item.downloadedProducts != null){
                           var productVersions = item.downloadedProducts.split(";");
                           item.proVersionInfoList = [];
                           angular.forEach(productVersions,function (info) {
                               item.proVersionInfoList.push(info);
                           });
                       }
                       if (item.downloadedTime != null){
                           var date = new Date(item.downloadedTime);
                           item.downloadedTime = date.format("yyyy-MM-dd hh:mm:ss");
                       }
                    });
                }
            });
            return result;
        };
        //第二个tab页面(历史记录)的加载方法
        $scope.load7 = function (){
            $scope.personsInfo = $scope.personsinfoGet();
            $scope.downloadhistoryrecordsGet();
        };


        //验收环节页面部分
        $scope.find = function () {
            if($scope.projectId == ''){
                return;
            }
            acceptanceService.find({projectId:$scope.projectId}).success(function (data) {
                if (data.result.length > 0 ){
                    $scope.list = data.result;
                    angular.forEach($scope.list,function (item) {
                        if (item.lastUpdate != null && item.lastUpdate > 0){
                            var date = new Date(item.lastUpdate);
                            item.lastUpdate = date.format("yyyy-MM-dd hh:mm:ss");
                        }
                    })
                } else {
                    $scope.list = [];
                }
            });
        };

        $scope.upload = function (item) {
            //弹出窗口
            var modalInstance = $modal.open({
                templateUrl: "upload.html",
                controller:uploadController,
                size:"lg",
                resolve: {
                    items: function () {
                        return {
                            item:item
                        };
                    }
                }
            });

            modalInstance.result.then(function (data) {
                $scope.find();
            });
        };

        $scope.downloadDocument = function (item) {
            var param = {
                id:item.id
            };
            acceptanceService.download(param).success(function (data) {
                if (data.errorMsg != null || data.errosMsg != undefined){
                    alert(data.errorMsg);
                } else {
                    var filePath = data.filePath;
                    console.log(filePath);
                    //特殊字符+，&转义处理
                    filePath = filePath.replace(/\+/g, "%2B");
                    filePath = filePath.replace(/\&/g, "%26");
                    window.location.href = "/api/acceptance/download?filePath=" + filePath;
                }
            });
        };

        //确认对话框定义
        $scope.confirmModal = function(result,confirmInfo){
            $scope.para = {
                result : result,
                info : confirmInfo
            };
            var modalInstance = $modal.open({
                templateUrl : 'confirm.html',
                controller : confirmCtrl,
                windowClass: "confirmModal",
                keyboard : true,
                backdrop : true,
                resolve : {
                    para : function () {
                        return angular.copy($scope.para);
                    }
                }
            });
            modalInstance.result.then(function() {
                //点击确认按钮之后的进行的操作

            });
        };


    };

    var confirmCtrl = ["$scope","$modal", "$modalInstance","para",function($scope,
        $modal, $modalInstance, para) {
        $scope.result = para.result;
        $scope.info = para.info;

        $scope.ok = function() {
            $modalInstance.close();
        };
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    }];

    var modalInstanceCtrl = ["$scope","$modal", "$modalInstance", "paras",function($scope,
        $modal, $modalInstance, paras) {

        //日期控件
        $scope.dateOptions = {
             startingDay: 1,
             class: 'datepicker'
        };
        //日期控件
        $scope.format = "yyyy-MM-dd";
        $scope.openDatepicker = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if(i==1){
                $scope.loanDate = true;
            }
        };

        $scope.openDatepicker1 = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if(i==1){
                $scope.loanDate1 = true;
            }
        };

        $scope.pros = paras.pros;
        $scope.opers = paras.teststarters;
        $scope.operators = paras.testers;

        //入参的产品，提测人，测试负责人改成对象
        $scope.newTestStartRecord = {
            production :  $scope.selectedProduct,
            versionNum :  "",
            testStarter : $scope.selectedTestStarter,
            loanDate : "",
            branchName : "",
            tester : $scope.selectedTester,
            loanDate1 :  "",
            smokeTestPassRate : "",
            returnNum :  "",
            configInfo :  ""
        };

        $scope.ok = function() {
            $modalInstance.close($scope.newTestStartRecord);
        };
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    }];

    var uploadController=["$scope","$modal", "$modalInstance","items","AcceptanceService",
        function ($scope, $modal,$modalInstance,items,acceptanceService) {
            $scope.item = items.item;
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
            $scope.upload = function () {
                var fd = new FormData();
                var files = document.querySelector('input[type=file]').files;
                if(files.length == 0){
                    $scope.loading = false;
                    $.Huimodalalert("请选择要上传的文件",1000);
                    return;
                }
                angular.forEach(files,function (file) {
                    fd.append('file[]', file);
                });
                fd.append('id',$scope.item.id);
                acceptanceService.upload(fd).success(function (data) {
                    if(data.errorMsg != null){
                        alert(data.errorMsg);
                    } else {
                        alert("上传成功！");
                        //关闭
                        $modalInstance.close($scope.item);
                    }
                });
            };
        }
    ];

    angular.module("cicd.projectstart",[])
        .controller("ProjectStartController",["$scope","$http","$modal","$location","projectstart_Service","online_testService",
            "develop_processService","online_deliveryService","AcceptanceService","toolsService",projectStartController])
        .service("toolsService",[function () {
            "use strict";
            /**
             * 获取网址上的参数
             * @param name  网址上的参数.例如（id）
             * @param url   网址连接。
             * @returns {*}  返回网址参数的值
             */
            this.parameter = function (name, url) {
                var parameterString = null;
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                parameterString = url.substr(url.indexOf("?"), url.length);//获取截取？以后的字符串
                var r = parameterString.substr(1).match(reg);
                if (r != null){
                    return  unescape(r[2]);
                }
                return null;
            };

            //日期转换函数
            Date.prototype.format = function(format){
                var o = {
                    "M+" : this.getMonth()+1, //month
                    "d+" : this.getDate(),    //day
                    "h+" : this.getHours(),   //hour
                    "m+" : this.getMinutes(), //minute
                    "s+" : this.getSeconds(), //second
                    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
                    "S" : this.getMilliseconds() //millisecond
                };
                if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
                    (this.getFullYear()+"").substr(4 - RegExp.$1.length));
                for(var k in o)if(new RegExp("("+ k +")").test(format))
                    format = format.replace(RegExp.$1,
                        RegExp.$1.length==1 ? o[k] :
                            ("00"+ o[k]).substr((""+ o[k]).length));
                return format;
            };
        }])

})();